package plugins.detail;

import kd.bos.base.AbstractBasePlugIn;
import kd.bos.bill.BillShowParameter;
import kd.bos.cache.CacheFactory;
import kd.bos.cache.DistributeSessionlessCache;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.serialization.SerializationUtils;
import kd.bos.form.ShowType;
import kd.bos.form.control.events.ItemClickEvent;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.sdk.plugin.Plugin;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CreatOrderAtDishes_takeaway extends AbstractBasePlugIn implements Plugin {

    public void itemClick(ItemClickEvent e) {
        super.itemClick(e);

        if (e.getItemKey().equalsIgnoreCase("dcb4_takeaway")) {
            DistributeSessionlessCache cache = CacheFactory.getCommonCacheFactory().getDistributeSessionlessCache("customRegion");

            cache.put("model", "takeaway"); // 存储标签值

            Long dishesID = (Long) this.getModel().getDataEntity().getPkValue();

            // Long dishesId = getMerchantIdByName((String)dishesID);

            Object price = this.getModel().getValue("dcb4_price");

            // 1. 获取商户ID字段值
            Object merchantIdObj = this.getModel().getValue("dcb4_merchant_id");
            Long merchantId = null;

            // 2. 尝试解析为纯数字ID
            if (merchantIdObj != null) {
                merchantId = parseMerchantId(merchantIdObj);
            }

            // 3. 如果无法获取纯数字ID，尝试通过商户名称查询
            if (merchantId == null) {
                String merchantName = getMerchantName();
                if (merchantName != null && !merchantName.isEmpty()) {
                    merchantId = getMerchantIdByName(merchantName);
                }
            }

            // 4. 如果仍然无法获取商户ID，显示错误信息
            if (merchantId == null) {
                this.getView().showMessage("无法获取有效的商户ID");
                return;
            }

            // 准备菜品数据
            List<Map<String, Object>> selecteddishData = new ArrayList<>();
            Map<String, Object> dishData = new HashMap<>();
            dishData.put("dishesID", dishesID);
            dishData.put("price", price);
            selecteddishData.add(dishData);

            // 序列化数据
            String selecteddishesdata = SerializationUtils.toJsonString(selecteddishData);
            String orderedmerchantid = String.valueOf(merchantId); // 纯数字字符串

            // 存入缓存
            cache.put("selecteddishesdata", selecteddishesdata);
            cache.put("orderedmerchantid", orderedmerchantid);

            // 打开目标页面
            BillShowParameter billShowParameter = new BillShowParameter();
            billShowParameter.setFormId("dcb4_order_history");
            billShowParameter.getOpenStyle().setShowType(ShowType.Modal);
            this.getView().showForm(billShowParameter);
        }
    }

    /**
     * 尝试从商户ID字段获取纯数字ID
     * @param merchantIdObj 商户ID字段值
     * @return 纯数字商户ID，如果无法解析返回null
     */
    private Long parseMerchantId(Object merchantIdObj) {
        if (merchantIdObj == null) {
            return null;
        }

        // 如果已经是Long类型，直接返回
        if (merchantIdObj instanceof Long) {
            return (Long) merchantIdObj;
        }

        // 如果是DynamicObject类型，获取其主键值
        if (merchantIdObj instanceof DynamicObject) {
            return (Long)((DynamicObject) merchantIdObj).getPkValue();
        }

        // 如果是字符串类型，尝试解析为Long
        if (merchantIdObj instanceof String) {
            try {
                return Long.parseLong((String) merchantIdObj);
            } catch (NumberFormatException e) {
                // 解析失败，尝试从字符串中提取数字
                String numericPart = ((String) merchantIdObj).replaceAll("[^0-9]", "");
                if (!numericPart.isEmpty()) {
                    try {
                        return Long.parseLong(numericPart);
                    } catch (NumberFormatException ex) {
                        // 忽略解析错误
                    }
                }
            }
        }

        return null;
    }

    /**
     * 获取商户名称
     * @return 商户名称，如果无法获取返回null
     */
    private String getMerchantName() {
        // 尝试获取商户对象
        DynamicObject merchantObj = (DynamicObject) this.getModel().getValue("dcb4_merchant");
        if (merchantObj != null) {
            return merchantObj.getString("name");
        }

        // 尝试直接获取名称字段
        Object nameObj = this.getModel().getValue("dcb4_merchant.name");
        if (nameObj instanceof String) {
            return (String) nameObj;
        }

        return null;
    }

    /**
     * 根据商户名称查询商户ID
     * @param merchantName 商户名称
     * @return 商户ID，如果未找到返回null
     */
    private Long getMerchantIdByName(String merchantName) {
        if (merchantName == null || merchantName.isEmpty()) {
            return null;
        }

        // 构建查询条件：名称等于传入的名称
        QFilter nameFilter = new QFilter("name", QCP.equals, merchantName);

        // 查询商户基础资料，只返回id字段
        DynamicObject merchant = QueryServiceHelper.queryOne("dcb4_merchant", "id", new QFilter[]{nameFilter});

        if (merchant != null) {
            return (Long)merchant.getPkValue();
        }

        return null;
    }
}